package com.yeswater.multithread.chapter3.test3_1.test1;

import java.util.concurrent.TimeUnit;

/**
 * author : yeswater
 * date : 2023/10/22
 */

public class Main {
    public static void main(String[] args) {
        MyList service = new MyList();
        ThreadA a = new ThreadA(service);
        a.setName("A");
        a.start();
        ThreadB b = new ThreadB(service);
        b.setName("B");
        b.start();
    }

    private static class ThreadA extends Thread{
        private MyList list;

        public ThreadA(MyList list) {
            this.list = list;
        }

        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    list.add();
                    System.out.println(" add " + (i + 1) + " element");
                    TimeUnit.SECONDS.sleep(1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static class ThreadB extends Thread{
        private MyList list;

        public ThreadB(MyList list) {
            this.list = list;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    // 轮询的时间长可能取不到想要的数据 5
                    Thread.sleep(2000);
                    if (list.size() == 5) {
                        System.out.println(" == 5, thread-b will exit");
                        throw new InterruptedException();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
